from typing import Optional, List

from sqlalchemy.orm.attributes import Mapped
from sqlmodel import Field, Relationship, SQLModel

from app.models import SQLBaseModel
from .base import IdType
from ..schemas.base_schema import RegionTypeEnum


class BaseRegion(SQLModel):
    code: str = Field(index=True, description="编码")
    name: str = Field(index=True, description="名称")
    type: Optional[RegionTypeEnum] = Field(
        default=None, index=True, description="地区类型"
    )
    description: Optional[str] = Field(default=None, description="描述")


class Region(SQLBaseModel, BaseRegion, table=True):
    __tablename__ = "region"

    """一对多自引用关系"""
    parent_id: Optional[IdType] = Field(
        default=None, index=True, foreign_key="region.id", description="上级ID"
    )
    # 系统使用假删除，所有不需要级联删除，后续自己处理删除逻辑
    """
    选项	描述
        save-update	自动将新对象添加到会话中
        merge	级联合并操作
        expunge	级联清除操作
        delete	级联删除操作
        delete-orphan	删除不再与父对象关联的子对象
        all	等同于 save-update, merge, expunge, delete
        none	禁用所有级联
    """
    children: List["Region"]= Relationship(
        back_populates="parent",
        sa_relationship_kwargs={"cascade": "save-update, merge","lazy": "raise"},
    )
    # 对于自引用关系，需要使用 sa_relationship_kwargs={"remote_side": [id]} 来指定关系的"远程端"
    parent: Optional["Region"] = Relationship(
        back_populates="children", sa_relationship_kwargs={"remote_side": "Region.id"}
    )
